var util = require('../../libs/util.js');
var app = getApp();
Page({
  data: {
    vehicleData: [],
    searchShowed: false,
    searchVal: "",
    selected: false,
    orderId: "",
    type: ''
  },
  onShareAppMessage: function () {
    return {
      title: app.appName,
      path: '/pages/index/index'
    }
  },
  onLoad: function (e) {
    wx.setNavigationBarTitle({
      "title": app.appName + "--选择车辆"
    });
    wx.showLoading({
      title: '加载中...',
      mask: true
    })
    this.setData({
      delivery: e.delivery,
      type: e.type,
      CO_ID: app.globalData.CO_ID,
      warehouse: e.warehouse,
      loadingDate: e.loadingDate,
      vehicleLength: e.vehicleLength,
      tags: e.tags
    })
    this.loadVehicleData();
  },
  onReady: function () {
    wx.hideToast()
  },
  bindInput: function (e) {
    var item = String(e.currentTarget.id),
      item_value = {};
    item_value[item] = e.detail.value;
    this.setData(item_value);
  },
  search: function () {
    this.loadVehicleData();
  },
  loadVehicleData() {
    var that = this;
    let condition = " a.CO_ID='" + app.globalData.CO_ID + "' and  a.BE_DEL=0 "
    if(this.data.searchVal){
      condition = " and (a.plate like '%"+this.data.searchVal+"%' or  b.name like '%"+this.data.searchVal+"%') "
    }
    util.postData("/zhc/datalist/getDataByListId", {
      "list_id": "F905AEC8-5754-4B14-83E2-672E45717039",
      "res": "",
      "page": {
        "size": 200,
        "current": 1,
        "orders": [{
          "column": "a.ADD_TIME",
          "asc": "false"
        }]
      },
      "data": {
        "field": "a.plate,a.driver,a.model,a.coord,a.district,a.total_oil,a.ADD_TIME,a.loadage,a.score,a.vehicle_register,a.vehicle_function,a.INSURANCE,a.tags,a.miles,a.plate_owner,a.temperature_current,a.oils,a.vehicle_size_out,a.vip,a.semitrailer_plate,a.loan_body,a.brand,a.loan_nper,a.province,a.latitude_current,a.iot_box,a.color,a.vehicleVolume,a.address,a.level,a.driver2,a.capacity_company,a.vip_to,a.is_work,a.photo,a.state,a.loan_month,a.ID,a.engineno,a.ischeck,a.buy_date,a.income_ratio,a.roadTC,a.longitude_current,a.cost,a.changeCompany,a.CO_ID,a.loan_first,a.carrier,a.station_address,a.last_keep_date,a.vin,a.approved_load,a.depreciation_ratio,a.truck_type,a.total_weight,a.vehicle_owner,a.img_vehicle_licence,a.mobile_warehouse,a.vehicleSizeWidth,a.vehicleSizeHeight,a.vehicleFunction,a.vehicleLength,a.vehicleSizeLength,a.plate_color,a.img_vehicle,a.station_coord,a.xyp_vehicle,a.operating_permit,a.contract,a.capacity_shipper,a.user_id,a.NO,a.depreciation_month_price,a.vehicle_spec_in,a.semitrailer,a.vehicleSource,a.tp_alarm,a.purchase_date,a.vehicle_key,a.max_speed,a.ADD_USER,a.purchase_price,a.is_oil,a.street,a.app_gps_first,a.vehicle_type,a.city,a.oldId,a.humidity_current,a.BE_DEL,a.DATA_CLIENT,a.DATA_DEPT,a.DATA_DEPT_TEXT,a.UPDATE_USER_NAME,a.DATA_ROLE,a.UPDATE_USER,a.ADD_USER_NAME,a.UPDATE_TIME,a.DATA_NO,a.driverName"
      },
      "repeat_field": [],
      "condition": condition,
      "virtual_field": [
        {
            "relate": "LEFT JOIN",
            "res": "88e65a5ccd734a35a0cac74c9d58ff2e",
            "alias": "b",
            "on": "a.driver=b.ID",
            "type": "",
            "condition": "",
            "from_field": "name",
            "field_name": "name",
            "field_alias": "司机"
        },
        {
            "relate": "LEFT JOIN",
            "res": "88e65a5ccd734a35a0cac74c9d58ff2e",
            "alias": "d",
            "on": "a.driver=d.ID",
            "type": "",
            "condition": "",
            "from_field": "phone",
            "field_name": "phone",
            "field_alias": "手机号码"
        }
    ]
    }, function (res, error) {
      console.log(res);
      console.log(error)
      wx.hideLoading();
      if (error) {
        return false;
      }
      if (res.data.success && res.data?.result?.records.length > 0) {
        that.setData({
          vehicleData: res.data.result.records
        })
      } else {
        that.setData({
          vehicleData: []
        });
      }
    });
  },
  vehicleSelect: function (e) {
    console.log(e)
    var vehicleData = this.data.vehicleData;
    for (var i = 0; i < vehicleData.length; i++) {
      vehicleData[i].checked = vehicleData[i].ID == e.detail.value;
      if (vehicleData[i].ID == e.detail.value) {
        this.setData({
          selected: true,
          vehicle: vehicleData[i]
        })
      }
    }
    this.setData({
      vehicleData: vehicleData
    });
  },
  confirmData: function () {
    var that = this;
    if (this.data.selected) {
      if (that.data.type == "assign") {
        wx.showLoading({
          title: '派车中...',
        });
        util.postData("/sys/form/commonUpdate",{
          "formId":"6E6999E1-1A6B-4F98-B1A4-A0A6BD77FAFC",
          "data":[{
              "dataId":that.data.delivery,
              "target":{"vehicle":that.data.vehicle.ID,"driver":that.data.vehicle.driver||''}
          }],
          "condition":""
          }, function (res, error) {
          console.log(res); console.log(error)
          wx.hideLoading();
          if (error) {
            return false;
          }
          if (res.data.success) {
            wx.showToast({
              title: '派车成功',
              icon: 'success',
              duration: 2000,
              success: function () {
                setTimeout(function () {
                  wx.redirectTo({
                    url: '/pages/schedule/schedule'
                  })
                }, 2000);
              }
            });
          }else{
            wx.showToast({
              title: '派车失败',
              image: '/images/wrong.png',
              duration: 3000
            });
          }
        });
      } else if (that.data.type == "change") {
        wx.showLoading({
          title: '更换车辆中...',
        });
        util.postData("/sys/form/commonUpdate",{
          "formId":"6E6999E1-1A6B-4F98-B1A4-A0A6BD77FAFC",
          "data":[{
              "dataId":that.data.delivery,
              "target":{"vehicle":that.data.vehicle.ID,"driver":that.data.vehicle.driver||''}
          }],
          "condition":""
          }, function (res, error) {
          console.log(res); console.log(error)
          wx.hideLoading();
          if (error) {
            return false;
          }
          if (res.data.success) {
            wx.showToast({
              title: '换车成功',
              icon: 'success',
              duration: 2000,
              success: function () {
                setTimeout(function () {
                  wx.redirectTo({
                    url: '/pages/schedule/schedule'
                  })
                }, 2000);
              }
            });
          }else{
            wx.showToast({
              title: '换车失败',
              image: '/images/wrong.png',
              duration: 3000
            });
          }
        });
      } else if (that.data.type == "report") {
        wx.setStorage({
          key: "vehicle",
          data: that.data.vehicle,
          complete: function (res) {
            wx.navigateBack({
              delta: 1
            });
          }
        });
      }
    } else {
      wx.showToast({
        title: "请选择车辆",
        image: "/images/wrong.svg",
        duration: 3000
      });
    }
  },
  cancelConfirmData: function () {
    if (this.data.type == "report") {
      wx.setStorage({
        key: "vehicle",
        data: {},
        complete: function (res) {
          wx.navigateBack({
            delta: 1
          });
        }
      });
    } else {
      wx.redirectTo({
        url: '/pages/schedule/schedule'
      })
    }
  }
});